<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2018/3/1
 * Time: 下午3:13
 */

namespace Admin\Frontend\Controllers;


use Admin\Models\crm\XhcustContact;
use Admin\Models\crm\XhcustInfo;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\school\XhsblFeedback;
use Admin\Models\school\XhsblGroup;
use Admin\Models\school\XhsblInfo;
use Admin\Models\school\XhsblPushLog;
use Admin\Models\school\XhsblTrack;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\user\XhsysUser;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\XhException;
use Modules\School;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class SchoolBookController extends ControllerBase
{

    /**
     * 检查是否为创建者
     *
     * @param $creator
     * @return bool
     * create by dale 20180315
     */
    public function checkSelfPower($creator){
        if(User::isAdmin()){
            return true;
        }
        if($creator == Main::getLoginUserInfo('userId')){
            return true;
        }
        return false;
    }


    public function extraPower($tag){
        if(User::isAdmin()){
            return true;
        }
        $deps = User::getExtraPower('dep',$tag);
        $userIds = Hrm::getUserByDepId($deps);
        $newArr = [];
        foreach ($userIds as $ids){
            $newArr =array_merge($newArr,$ids);
        }
        $newArr = array_values(array_filter($newArr));

        return $newArr;
    }



    public  $iState = [ 1 => '未同意', 2 => '已同意'];


    /**
     * 首页
     *
     * create by dale 20180427
     */
    public function homeAction()
    {
        $this->view->pick('school_book/home');
        Assets::select2();
        Assets::easyUI('js/school_book/home.js');
        $builder = $this->modelsManager->createBuilder()
            ->columns('i.iSBLId,i.iSchoolId,i.iSBGId,i.iSBEId,i.mContent,i.bResult,i.iState,i.bDelete,s.sSchoolName,i.tCreateDate,i.iCreateUserId,i.tLastModifyDate,i.iLastModifyUserId')
            ->from(['i'=>'Admin\\Models\\school\\XhsblInfo'])
            ->leftJoin('Admin\\Models\\school\\XhschoolInfo', 'i.iSchoolId = s.iSchoolId', 's')
            ->where('i.bDelete = 0');
        if (!User::isAdmin()) { //不是admin自能看到自己创建的
            $loginId = Main::getLoginUserInfo('userId');
            $depTag  = Main::getLoginUserInfo('depTag');
            if (in_array('XHYYB', $depTag)) { //运营部
                $builder->andWhere('i.iSchoolId in ({schoolIds:array}) ', ['schoolIds' => User::getSchoolPower(false, null, false) ]);
            } else { //不是运营部
                if (!User::getExtraPower('dep', 'schoolBook', $loginId, true)) {
                    $builder->andWhere('i.iCreateUserId = :iCreateUserId:', ['iCreateUserId' =>$loginId ]);
                } else { //有额外权限
                    $builder->andWhere('i.iCreateUserId = :iCreateUserId: OR i.iCreateUserId in ({ids:array}) ', ['iCreateUserId' =>$loginId,'ids'=> $this->extraPower('schoolBook') ]);
                }
            }
        }
        $data = $builder->getQuery()->execute()->toArray();
        foreach ($data as $index => &$row) {
            $row['iState'] = $this->iState[$row['iState']];
        }
        unset($row);
        $this->view->setVars([
           'books' => $data ,
        ]);
    }

    /**
     * 首页详情
     *
     * create by dale 20180427
     */
    public function homeDetailAction()
    {
        $schoolName = $this->request->getQuery('schoolName' , 'string');
        $iSBLId     = $this->request->getQuery('iSBLId' , 'int');
        $this->view->pick('school_book/homeDetail');

        $this->view->setVars([
            'schoolName' => $schoolName,
            'iSBLId' => $iSBLId,
        ]);
    }




    /**
     * 校本库列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale 20180305
     */
    public function indexAction()
    {
        $this->view->pick('school_book/index');
        Assets::select2();
        Assets::easyUI('js/school_book/index.js');
        $listButtonArr = $formButtonArr = $listSearchArr = [];
        $listButtonArr[] = array('plain'=>'true' ,'id'=>'bt_list_add', 'text'=>'增加', 'icon'=>'fa-plus');
        $listButtonArr[] = array('plain'=>'true' ,'id'=>'bt_list_del', 'text'=>'删除', 'icon'=>'fa-trash');
        $listSearchArr[] = array('type'=>'text', 'id'=>'list_search_vague', 'label'=>' 搜索： ');
        return $this->view->setVars(array(
            'List'       => Template::createList('list', 'School_Book', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'Form'       => true,
        ));
    }

    /**
     * 删除信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180324
     */
    public function delInfoAction(){
        try{
            $iSBLId = $this->request->getPost('iSBLId');
            if(!$iSBLId){
                return $this->sendErrorResponse(400,'缺少参数');
            }
            $obj = XhsblInfo::findFirst($iSBLId);
            if(!$obj){
                return $this->sendErrorResponse(500,'记录未找到');
            }
            $obj->bDelete = 1;
            if(!$obj->save()){
                return $this->sendErrorResponse(500,'保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }


    /**
     * 获取校本库数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180306
     */
    public function getListAction(){
        try{
            $key = $this->request->getPost('key' , 'string');
            $builder = $this->modelsManager->createBuilder()
                ->columns('i.iSBLId,i.iSchoolId,i.iSBGId,i.iSBEId,i.mContent,i.bResult,i.iState,i.bDelete,s.sSchoolName,i.tCreateDate,i.iCreateUserId,i.tLastModifyDate,i.iLastModifyUserId')
                ->from(['i'=>'Admin\\Models\\school\\XhsblInfo'])
                ->leftJoin('Admin\\Models\\school\\XhschoolInfo','i.iSchoolId = s.iSchoolId','s')
                ->where('i.bDelete = 0');
            if(!User::isAdmin()){ //不是admin自能看到自己创建的
                $loginId = Main::getLoginUserInfo('userId');
                $depTag  = Main::getLoginUserInfo('depTag');
                if ( in_array('XHYYB' , $depTag) ) { //运营部
                    if (School::getPower() !== true){
                        $builder->andWhere('i.iSchoolId in ({schoolIds:array}) ' , ['schoolIds' => School::getPower() ]);
                    }
                } else { //不是运营部
                    if(!User::getExtraPower('dep','schoolBook',$loginId,true)){
                        $builder->andWhere('i.iCreateUserId = :iCreateUserId:' , ['iCreateUserId' =>$loginId ]);
                    }else{ //有额外权限
                        $builder->andWhere('i.iCreateUserId = :iCreateUserId: OR i.iCreateUserId in ({ids:array}) ' , ['iCreateUserId' =>$loginId,'ids'=> $this->extraPower('schoolBook') ]);
                    }
                }
            }
            if ($key) {
                $schoolIds = School::searchSchool($key, true);
                $builder->andWhere('i.iSchoolId in ({searchSchools:array})' , ['searchSchools' => $schoolIds]);
            }
            $data = Main::runBuilderPage($builder);
//        $ids  = array_column($data['rows'], 'iSBLId');
            foreach ($data["rows"] as $index => $row) {
                if ($row['iState'] == 1) {
                    $data["rows"][$index]['iState'] = '<small class="badge  badge-square " title="8" style="color: white;background-color: orangered">'.$this->iState[$row['iState']].'</small>';
                } else if ($row['iState'] == 2) {
                    $data["rows"][$index]['iState'] = '<small class="badge  badge-square " title="8" style="color: white;background-color: green">'.$this->iState[$row['iState']].'</small>';
                }
                $data["rows"][$index]['progress'] = '<a nodeId="' . $row['iSBLId'] . '" class="progress" style="width: 100%" onclick="showProgress(this)"><i  class="fa fa-clock-o" aria-hidden="true" style="font-size: 20px;"></i></a>';
            }
            Main::runUserNameById($data['rows'],['iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'iLastModifyUserId'],true);
            return $this->sendJsonResponse($data);
        }catch (\Exception $e){
            return $this->sendErrorResponse(500 ,$e->getMessage());
        }
    }


    /**
     * 添加表单
     *
     * create by dale 20180306
     */
    public function addFormAction(){
        $this->view->pick('school_book/addForm');
        Assets::select2();
        Assets::datetimePicker();
        $schools = User::getSchoolPower(true); //自己权限下的学校
        $this->view->setVars([
            'schools' => $schools
        ]);
    }

    /**
     * 创建校本库
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180306
     */
    public function createInfoAction(){
        $schoolId = $this->request->getPost('schoolId');
        $data = $this->request->getPost();
        try{
            if(!$schoolId){
                return $this->sendErrorResponse(400,'缺少参数');
            }
            $info = XhsblInfo::findFirst([
                'conditions' => 'bDelete = 0 AND iSchoolId = :iSchoolId:',
                'bind'       =>  ['iSchoolId' => $schoolId],
            ]);
            if($info){
                return $this->sendErrorResponse(400,'学校已创建');
            }
            $obj = new XhsblInfo();
            $obj->iSchoolId = $schoolId;
            $obj->assign($data);
            $obj->iState = $obj->bResult == 1 ? 2 : 1;
            if(!$obj->save()){
                return $this->sendErrorResponse(500,'创建失败');
            }
            return  $this->sendSuccessResponse('创建成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 保存沟通信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180367
     */
    public function saveInfoAction()
    {
        $post = $this->request->getPost();
        try {
            $this->db->begin();
            if (!isset($post['iSBLId'])) {
                return $this->sendErrorResponse(400, '缺少id');
            }
            $obj = XhsblInfo::findFirst($post['iSBLId']);
            $obj->assign($post);
            $obj->iState = $obj->bResult == 1 ? 2 : 1;
            if (!$obj->save()) {
                throw new \Exception('保存失败');
            }
            $track = new XhsblTrack();
            $track->iTrackTime = strtotime($obj->tTime);
            $track->mContent = $obj->mContent;
            $track->iSBLId = $obj->iSBLId;
            if (!$track->save()) {
                throw new \Exception('保存失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 校本库标签选项卡
     *
     * @param $id
     * create by dale 20180306
     * create by dale 20180306
     */
    public function schTabAction($id = null)
    {
        if (!$id) {
            return $this->sendViewError('缺少参数');
        }
        $info = XhsblInfo::findFirst($id)->toArray();
        $this->view->pick('school_book/schTab');
        Assets::importJs('../customer/js/myMain.js');
        Assets::importJs('js/school_book/schTab.js');
        $infos = [$info];
        Main::runUserNameById($infos, ['iCreateUserId' => 'iCreateUserId',
            'iLastModifyUserId' => 'iLastModifyUserId'], true);
//        $str = '创建人：'.$infos[0]['iCreateUserId'].'&nbsp;&nbsp;创建时间：'.$infos[0]['tCreateDate'].',最后修改人：'.$infos[0]['iLastModifyUserId'].'&nbsp;&nbsp;最后修改时间：'.$infos[0]['tLastModifyDate'];
        $this->view->setVars([
            'bResult' => $info['bResult'],
            'iSBLId'  => $info['iSBLId'],
            'info'    => json_encode($info),
//            'createStr' => $str,
        ]);
    }

    /**
     * 获取沟通信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180906
     */
    public function getTrackAction()
    {
        try {
            $id = $this->request->getPost('id', 'int');
            $trackArr = XhsblTrack::find([
                'conditions' => 'bDelete= 0 and iSBLId = :iSBLId:',
                'bind' => ['iSBLId' => $id],
                'order' => 'iTrackTime desc',
            ])->toArray();
            if (!$trackArr) {
                return $this->sendJsonResponse([]);
            }
            $trackInfo = [];
            Main::runUserNameById(
                $trackArr,
                ['iCreateUserId' => 'sCreateUserName', 'iLastModifyUserId' => 'sLastModifyUserName'],
                true
            );
            foreach ($trackArr as $track) {
                $track['iTrackTime'] = date('Y-m-d', $track['iTrackTime']);
                $trackInfo[] = [
                    'id'    => $track['iSBLTId'],
                    'title' => $track['iTrackTime'],
                    'time' => $track['iTrackTime'],
                    'content' => str_replace(array("\r\n", "\r", "\n"), '<br>', $track['mContent']),
                    'footer' => array(
                        'left' => '修改时间:' . $track['tLastModifyDate'] . '&nbsp;&nbsp;修改人:' . $track['sLastModifyUserName'],
                        'right' => '创建时间:' . $track['tCreateDate'] . '&nbsp;&nbsp;创建人:' . $track['sCreateUserName'],
                    ),
                    'showDel' => true
                ];
            }
            return $this->sendJsonResponse($trackInfo);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 删除日志
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180906
     */
    public function delTrackAction()
    {
        try {
            $id = $this->request->getPost('id', 'int');
            $obj = XhsblTrack::findFirst($id);
            $obj->bDelete = 1;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '删除失败');
            }
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }



    /**
     * 组织树
     *
     * create by dale 20180309 \弃用
     */
//    public function groupTreeAction(){
//        $iSBLId = $this->request->getQuery('iSBLId');
//        $this->view->pick('school_book/groupTree');
//        Assets::easyUI();
//        Assets::importJs('js/school_book/groupTree.js');
//        $this->view->setVars([
//            'iSBLId' => $iSBLId
//        ]);
//    }

    /**
     * 组织树
     *
     * create by dale 2018/3/19
     */
    public function groupOrgAction(){
        $iSBLId = $this->request->getQuery('iSBLId');
        $this->view->pick('school_book/groupOrg');
        Assets::easyUI();
        Assets::importJs('js/school_book/groupOrg.js');
        $this->view->pick('coop/coopList');
        Template::exists('School_BookGroup', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_shortcut', 'text' => '快捷添加', 'icon' => 'fa-plus');
//        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
//        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        $gradeEnum     = $this->getGradeSubject()['grade'];
        $subjectEnum   = XhsysEnum::getEnumByNodeName('学科');
        $listSearchArr[] = array('type' => 'select', 'id' => 'list_grade', 'data'=>$gradeEnum + ['' => '—年级—'], 'default'=>'');
        $listSearchArr[] = array('type' => 'select', 'id' => 'list_subject', 'data'=>$subjectEnum + ['' => '—学科—'], 'default'=>'');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        return $this->view->setVars([
            'List'       => Template::createList('list', 'School_BookGroup', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'iSBLId'  => $iSBLId,
        ]);
    }

    /**
     * 获取组织
     *
     * create by dale 20180309
     */
    public function getGroupAction(){
        try{
            $iSBLId  = $this->request->getPost('iSBLId','int');
            $key     = $this->request->getPost('key','string');
            $grade   = $this->request->getPost('grade','int');
            $subject = $this->request->getPost('subject','string','');
            if (!$iSBLId) {
                return $this->sendJsonResponse([]);
            }
            $parent = XhsblGroup::findFirst([
                'conditions' => 'iSBLId = :iSBLId: and bDelete = 0 and iParentId = 0',
                'bind'       => ['iSBLId' => $iSBLId]
            ]);
            if (!$parent){
                return $this->sendJsonResponse([]);
            }
            $builder = $this->modelsManager->createBuilder()
                ->from('Admin\Models\school\XhsblGroup')
                ->columns('*')
                ->where('bDelete = 0 and iParentId = :iSBGId:', ['iSBGId' => $parent->iSBGId] );
            if ($grade) {
                $builder->andWhere('iGrade = :grade:', ['grade' => $grade]);
            }
            if ($subject !== '') {
                $builder->andWhere('iSubject = :subject:', ['subject' => $subject]);
            }
            $builder->orderBy('iGrade asc,iSubject asc');
            $data = $builder->getQuery()->execute()->toArray();
            $gradeEnum = $this->getGradeSubject()['grade'];
            $subjectEnum = XhsysEnum::getEnumByNodeName('学科');
            foreach ($data as &$row) {
                $row['iGrade']     = isset($gradeEnum[$row['iGrade']]) ? $gradeEnum[$row['iGrade']] : '';
                $row['iChargeAll'] = $parent->iChiefId;
                $row['iSubject']   = isset($subjectEnum[$row['iSubject']]) ? $subjectEnum[$row['iSubject']] : '';
            }
            unset($row);
            Main::runUserName($data, ['iChiefId'=>'iChiefId', 'sChargeIds' =>'sChargeIds', 'iChargeAll' => 'iChargeAll',
                'iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId'], true);
            if ($key) {
                foreach ($data as $index => $row ) {
                    if (strpos($row['sChargeIds'], $key) === false && strpos($row['iSubject'], $key) === false && strpos($row['iGrade'], $key) === false ) {
                        unset($data[$index]);
                    }
                }
                $data = array_values($data);
            }
            return $this->sendJsonResponse($data);
        }catch (\Exception $e){
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

//    public function recursionForArray($parentId,$iSBLId,$users,$subjects){
//        $parameters = [
//            'conditions' => "bDelete=:bDelete: AND iParentId=:parentId: AND iSBLId = :iSBLId: ",
//            'bind'       => ['parentId' => $parentId , 'iSBLId' => $iSBLId , 'bDelete' => 0 ],
//        ];
//        $objs = XhsblGroup::find($parameters);
//        if ($objs == null) {
//            return [];
//        }
//        $array = $objs->toArray();
//        $newArray = [];
//        foreach ($array as $key => $value){
//            $value['sSubject']      = isset($value['iSubject']) ? $subjects[$value['iSubject']] : '专项组';
//            $value['sChief']        = $this->replaceName($value['iChiefId'],$users);
//            $value['sChargeIds']    = $this->replaceName($value['sChargeIds'],$users,true);
//            $newArray[$key] = $value ;
//            $newArray[$key]['children'] = $this->recursionForArray($value['iSBGId'],$iSBLId,$users,$subjects);
//            if( count($newArray[$key]['children']) == 0){
//                unset($newArray[$key]['children']);
//            }
//        }
//
//        return $newArray;
//    }

    /**
     * 姓名替换方法
     *
     * @param $id
     * @param $users
     * @param bool $multiple
     * @return string | array
     *
     * create by dale 20180315
     * modify by dale 20180319 返回数组
     */
    public function replaceName($id,$users,$multiple = false){
        if(!$id){
            return '';
        }
        if($multiple){
            $ids = explode(',',$id);
            if(count($ids) < 0){
                return '';
            }
            $arr = [];
            foreach ($ids as $id){
                $arr[] = $users[$id];
            }
            return $arr;

        }else{
            return $users[$id];
        }

    }

    /**
     * 新增组织表单
     *
     * @param $iSBLId 校本库id
     * @param $parentId = 0
     *
     *  create by dale 20180309
     *
     */
    public function groupFormAction($iSBLId,$parentId = 0){
        $iSBGId = $this->request->getQuery('iSBGId');
        $this->view->pick('school_book/groupForm');
        Assets::select2();
        Assets::importJs('js/school_book/groupForm.js');
        $schoolId = XhsblInfo::findFirst($iSBLId)->iSchoolId;
        $contacts = $this->getContact($schoolId);

        $webVars = [
            'parentId' => $parentId,
            'contacts' => $contacts,
            'subjects' => XhsysEnum::getEnumByNodeName('学科'),
            'iSBLId' => $iSBLId,
        ];
        if(!$iSBGId){
            $showCharges = $parentId == 0 ? false : true;
        }else{
            $info = XhsblGroup::findFirst($iSBGId);
            $webVars['info'] = json_encode($info->toArray());
            $showCharges = $info->iLevel == 1 ? false : true;
            if(!$this->checkSelfPower($info->iCreateUserId) && !$this->checkSelfPower($info->iChiefId)){ //负责人
                $webVars['check'] = '<script>parent.document.getElementById("bt_modal_confirm").style.display="none";</script>';
            }
        }

        $webVars['showCharges'] = $showCharges;

        $this->view->setVars($webVars);
    }

    /**
     * 组织架构图编辑界面
     *
     * @param $iSBLId
     * @param $iSBGId
     *
     * create by dale 20180316
     * modify by dale 20180319 编辑界面修改
     *
     */
    public function addTotalGroupAction($iSBLId){
        $this->view->pick('school_book/addTotalGroup');
        Assets::select2();
        Assets::importJs('js/school_book/jquery.serializejson.js');
        Assets::importJs('js/school_book/addTotalGroup.js');
        $schoolId = XhsblInfo::findFirst($iSBLId)->iSchoolId;
        $contacts = $this->getContact($schoolId);
        $subjects = XhsysEnum::getEnumByNodeName('学科');
        $grade    = $this->getGradeSubject()['grade'];
        $this->view->setVar('grade', $grade);
        $arr = [];
        foreach ($subjects as $index => $subject) {
            if($subject == '语文' || $subject == '数学' || $subject == '英语' || $subject == '科学'){
                $arr[] = $index;
            }
        }
        $webArr = [
            'contacts' => $contacts,
            'subjects' => $subjects,
            'iSBLId'   => $iSBLId,
            'selected' => json_encode($arr),
        ];
        $parent = XhsblGroup::findFirst([
            'conditions' => 'bDelete = 0 and iSBLId=:iSBLId: and iParentId = 0',
            'bind'       => ['iSBLId' => $iSBLId],
        ]);
        if ($parent) {
            $webArr['info'] = json_encode($this->getTotal($parent->iSBGId));
        }

        $this->view->setVars($webArr);
    }

    /**
     * 获取总共的json
     *
     * create by dale 20180319
     */
    public function getTotal($iSBGId){
        $parent   = XhsblGroup::findFirst($iSBGId);
        $children = XhsblGroup::find([
            'conditions' => 'bDelete = 0  AND iParentId = :iParentId:',
            'bind'       => ['iParentId' => $iSBGId]
        ]);
        return  array_merge([$parent->toArray()],$children->toArray());
    }


    /**
     * 保存全部借口，goup
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180319
     */
    public function saveGroupAllAction(){
        try{
            $arrs = $this->request->getPost('data');
            foreach ($arrs as $index => $arr){
                if(isset($arr['iParentId'])){
                    $first = $arr;
                    unset($arrs[$index]);
                }
                if(isset($arr['sChargeIds'])){
                    $arrs[$index]['sChargeIds'] = implode(',',$arr['sChargeIds']);
                }
            }
            $arrs = array_values($arrs);
            $this->db->begin();//开启事务
            if(isset($first['iSBGId']) && $first['iSBGId'] !=''){
                $firstObj = XhsblGroup::findFirst($first['iSBGId']);
            }else{
                $firstObj = new XhsblGroup();
            }

            $firstObj->assign($first);
            if(!$firstObj->save()){
                $this->db->rollback();
                return $this->sendErrorResponse(500,'保存失败');
            }
            foreach ($arrs as $arr){
                if(isset($arr['iSBGId']) && $arr['iSBGId'] !='' ){
                    $obj = XhsblGroup::findFirst($arr['iSBGId']);
                }else{
                    $obj = new XhsblGroup();
                }
                $obj->assign($arr);
                $obj->iParentId = $firstObj->iSBGId;
                if(!$obj->save()){
                    $this->db->rollback();
                    return $this->sendErrorResponse(500,'保存失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');

        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 获取联系人
     *
     * @param $schoolId
     * @return array
     *
     * create by dale 20180316
     */
    public function getContact($schoolId){
        $users = XhsysUser::find([
            'columns'    => 'iUserId,sUserName',
            'conditions' => 'bDelete = 0 AND iSchoolId=:iSchoolId: AND iUserType = 4 and bDisable = 0 and bHistory = 0 ',
//            'conditions' => 'bDelete = 0 AND iSchoolId=:iSchoolId: AND iUserType = 4 and bCompany = 0 and bDisable = 0 and bHistory = 0 ',
            'bind'       => ['iSchoolId' => $schoolId]
        ]);
        return array_column($users->toArray(),'sUserName','iUserId');
    }

    /**
     * 获取grade Subject,以及关系接口
     *
     * @return array|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     */
    public function getGradeSubject(){
        $url = Main::getConfigByName('resServerInterface')['questionBaseUrl'];
        $client   = new HttpClient($url);
        $response = $client->get('api/v1/dictionaries');
        if (!$response->isSuccess()){
            return $this->sendErrorResponse(500,$response->toArray()['msg'] ?:'调取接口失败',$response);
        }
        $data = $response->toArray();
        $subjects = [];
        $grades = [];
        foreach ($data as $index =>$row){
            if($row['paramType'] == 'subject'){
                $subjects[$row['id']] = $row['name'];
            }else if($row['paramType'] == 'grade'){
                $grades[$row['id']] = $row['name'];
            }
        }

        $response = $client->get('api/v1/books/textBookVersionCompare');
        if (!$response->isSuccess()){
            return $this->sendErrorResponse(500,$response->toArray()['msg'] ?:'调取接口失败',$response);
        }
        $relation = $response->toArray();

        return ['grade'=>$grades,'subject'=>$subjects,'relation'=>$relation];
    }



    /**
     * 保存Group
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180316
     */
    public function saveGroupAction(){
        $data = $this->request->getPost();
        if(isset($data['iSBGId'])){
            $group = XhsblGroup::findFirst($data['iSBGId']);
        }else{
            $group = new XhsblGroup();
        }
        $group->assign($data);
        if(isset($data['sChargeIds'])){
            $group->sChargeIds  = implode(',',$data['sChargeIds']);
        }
        if(!$group->save()){
            return $this->sendErrorResponse(500,'保存失败');
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 删除Group
     *
     * create by dale 20180316
     */
    public function delGroupAction(){
        $ids = $this->request->getPost('ids');
        if(!is_array($ids)){
            $ids = explode(',',$ids);
        }
        $res = XhsblGroup::deleteRecord('iSBGId',$ids);
        if(!$res){
            return $this->sendErrorResponse(400,'删除失败');
        }
        return $this->sendSuccessResponse('删除成功');
    }

    /**
     * 推进日志
     *
     * create by dale 20180316
     */
    public function pushLogAction(){
        $this->view->pick('school_book/pushLog');
        Assets::importJs('js/school_book/myMain.js');
        Assets::importJs('js/school_book/pushLog.js');
    }

    /**
     * 日志表单
     *
     * @param $iSBLId
     * @param $iSBEId
     * create by dale 2018/3/19
     */
    public function logFormAction($iSBLId = null, $iSBEId = null)
    {
        $this->view->pick('school_book/logForm');
        Assets::select2();
        Assets::datetimePicker();
        Assets::importJs('js/school_book/logForm.js');
        $schoolId = XhsblInfo::findFirst($iSBLId)->iSchoolId;
        $users = XhsysUser::find([
            'columns' => 'sUserName,iUserId',
//            'conditions' => 'iSchoolId = :schoolId: AND iUserType = 4 and  bDelete = 0 and bCompany = 0 and bDisable = 0 and bHistory = 0 ',
            'conditions' => 'iSchoolId = :schoolId: AND iUserType = 4 and  bDelete = 0 and bDisable = 0 and bHistory = 0 ',
            'bind' => ['schoolId' => $schoolId],
        ])->toArray();
        $users = array_column($users, 'sUserName', 'iUserId');
        $gradeSubject = $this->getGradeSubject();
        $webArr = [
            'iGrade' => $gradeSubject['grade'],
            'users' => $users,
            'iSBLId' => $iSBLId,
        ];

//        XhhrmStaff::getDepStaff()
        $data = Hrm::getDepStaffByTag('xhjxb');
        $staff = [];
        foreach ($data as $k => $v) {
            $staff[$k]['id'] = $k;
            $staff[$k]['text'] = $v;
        }
        $webArr['jsb'] = $staff;
        if($iSBEId){
            $info = XhsblPushLog::findFirst($iSBEId);
            $webArr['info'] = json_encode($info);
        }
        $this->view->setVars($webArr);
    }

    /**
     * 获取subject
     * 
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * 
     * create by dale 20180320
     */
    public function getSubjectAction(){
        $gradeId = $this->request->getPost('gradeId');
        $arr = $this->getGradeSubject();
        $result = [];
        foreach ($arr['relation'] as $index =>$row){
            if($row['gradeId'] == $gradeId){
                $result[$row['subjectId']] = $arr['subject'][$row['subjectId']];
            }
        }
        return $this->sendJsonResponse($result);
    }

    /**
     * 保存日志
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180319
     */
    public function saveLogAction(){
        try{
            $data = $this->request->getPost();
            if($data['iSBEId']){
                $obj = XhsblPushLog::findFirst($data['iSBEId']);
            }else{
                $obj =  new XhsblPushLog();
            }
            $obj->assign($data);
            if(isset($data['sChapterIds'])){
                $obj->sChapterIds = implode(',',$data['sChapterIds']);
            }
            if(!$obj->save()){
                return $this->sendErrorResponse(500,'保存失败');
            }
            return $this->sendSuccessResponse('成功');
        }catch(\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 获取日志列表
     * @param $iSBLId
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180319
     */
    public function getLogAction($iSBLId=null)
    {
        $traces = XhsblPushLog::find([
            'conditions' => 'bDelete = 0 AND iSBLId = :iSBLId:',
            'bind'       => ['iSBLId' => $iSBLId],
            'order'      => ' tCreateDate desc',
        ])->toArray();
        if(count($traces) <= 0){
            return $this->sendJsonResponse([]);
        }
        $gradeAndSubject = $this->getGradeSubject();
        $bookIds = array_column($traces,'sBookId');
        $books   = $this->getBooks($bookIds);
        $enums = ['iGrade'=>$gradeAndSubject['grade'],'iSubject'=>$gradeAndSubject['subject'],'books'=>$books];
        return json_encode(array(
            'showDelete' => true,
            'showEdit' => true,
            'data' => $this->pkLogData($traces,$enums),
        ));

    }

    /**
     * 根据传入的bookId获取book目录
     *
     * @param $bookIds
     * @return array|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180320
     */
    public function getBooks($bookIds){
        $arr = [];
        $baseUrl =  Main::getConfigByName('resServerInterface')['questionBaseUrl'];
        $client = new HttpClient($baseUrl);
        $params =[
            'textBookVersion' => 1,
            'gradeId'         => 1,
            'subjectId'       => 1
        ];
        foreach ($bookIds as $bookId){ //获取书目录
            $response = $client->get('/api/v1/books/'.$bookId.'/catalogs/coach',$params);
            if (!$response->isSuccess()){
                continue;
            }
            $data = $response->toArray();
            if(isset($data['catalogs']) && is_array($data['catalogs'])){
                foreach ($data['catalogs']  as $key => $val){
                    if($val['parentCatalogId'] != 0){ //去除子章节
                        unset($data['catalogs'][$key]);
                    }
                }
                $data['catalogs'] = array_values($data['catalogs']);
            }

            $book[$data['bookId']] = $data['bookName'];
            $catalogs = array_column($data['catalogs'],'catalogName','catalogId');
            $arr[$data['bookId']] = ['book'=>$book,'catalogs'=>$catalogs];
        }
        return $arr;
    }

    /**
     * 获取真实题量
     *
     * @return int|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180327
     */
    public function getRealNumAction(){
        $bookId = $this->request->getPost('bookId');
        $chapters = $this->request->getPost('chapters');
        $total = 0;
        $baseUrl =  Main::getConfigByName('resServerInterface')['questionBaseUrl'];
        $client = new HttpClient($baseUrl);
        $params =[
            'textBookVersion' => 1,
            'gradeId'         => 1,
            'subjectId'       => 1
        ];
        $response = $client->get('/api/v1/books/'.$bookId.'/catalogs/coach',$params);
        if (!$response->isSuccess()){
            return $total;
        }
        $data = $response->toArray();
        if(isset($data['catalogs']) && is_array($data['catalogs'])){
            foreach ($data['catalogs']  as $key => $val){
                if($val['parentCatalogId'] != 0){ //去除子章节
                    unset($data['catalogs'][$key]);
                }
            }
            $catalogs = array_column($data['catalogs'],'count','catalogId');
            foreach ( $chapters as $chapter){
                $total += isset($catalogs[$chapter]) ? $catalogs[$chapter] : 0;
            }
        }

        return $this->sendJsonResponse(['total'=>$total]);

    }

    /**
     * 删除日志
     *
     *
     * create by dale 20180320
     */
    public function delLogAction(){
        $iSBEId = $this->request->getPost('iSBEId');
        if(!$iSBEId){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $log = XhsblPushLog::findFirst($iSBEId);
        $log->bDelete = 1 ;
        if(!$log->save()){
            return $this->sendErrorResponse(500,'保存失败');
        }
        return $this->sendSuccessResponse('成功');
    }

    /**
     * 日志数据
     *
     * @param $traces
     * @param $enums
     *
     * @return array|mixed
     *
     * create by dale 20180316
     */
    public function pkLogData($traces,$enums){
        $flag = false;
        if(!is_array($traces)){
            $traces = [$traces];
            $flag = true;
        }
        $arr = [];
        Main::runUserNameById($traces, ['iLastModifyUserId'=>'iLastModifyUserId','iCreateUserId'=>'iCreateUserId','iChargeId'=>'iChargeId','iTchId'=>'iTchId'], true);

        foreach ( $traces as $trace) {
            $item = [];
            $item['id'] = $trace['iSBEId'];
            $item['time'] = $trace['tCreateDate'];
            $item['title'] = '<b>开始时间：</b>&nbsp;' . $trace['tStartTime'] . '&nbsp;&nbsp;<b>结束时间：</b>&nbsp;&nbsp;' . $trace['tEndTime'] . '&nbsp;&nbsp;<b>项目对接人：</b>&nbsp;' . $trace['iChargeId'];

            $item['retain']  = '<table class="sbTable">';
            $item['retain'] .= '<tr><td style="width: 40px;"><b>年级：</b></td><td style="width: 70px">'. (isset($enums['iGrade'][$trace['iGrade']]) ? $enums['iGrade'][$trace['iGrade']] : ''  ).'</td><td style="width: 40px;"><b>学科：</b></td><td  style="width: 70px">'.(isset($enums['iSubject'][$trace['iSubject']]) ? $enums['iSubject'][$trace['iSubject']] : '' ).'</td><td style="width: 40px;"><b>老师：</b></td><td style="width: 70px">'.$trace['iTchId'].'</td><td style="width: 40px;">';
            if(isset($enums['books'][$trace['sBookId']]['book'][$trace['sBookId']])){
                $item['retain'] .= '<b>题库：</b></td><td>'.$enums['books'][$trace['sBookId']]['book'][$trace['sBookId']].'</td></tr>';
            }else{
                $item['retain'] .= '<b>题库：</b></td><td></td></tr>';
            }
            if(isset($enums['books'][$trace['sBookId']]['catalogs'])){
                $chapters = $this->replaceArr($trace['sChapterIds'],$enums['books'][$trace['sBookId']]['catalogs'] );
                $chapters = explode(',',$chapters);
                if(count($chapters) > 0){
                    $item['retain'] .= '<tr><td rowspan="'.count($chapters).'" valign="top"><b>章节：</b></td><td colspan="7">'.$chapters[0].'</td></tr>';
                    foreach ($chapters as $index=>$chapter){
                        if($index == 0){
                            continue;
                        }else{
                            $item['retain'] .= '<tr><td colspan="7">'.$chapter.'</td></tr>';
                        }
                    }
                }
            }else{
                $item['retain'] .= '<tr><td valign="top"><b>章节：</b></td><td colspan="7"></td></tr>';
            }

            $item['retain'] .= '<tr><td><b>题量：</b></td><td>'.$trace['iQuestionNum'].'</td></tr>';
            $item['retain'] .= '<tr><td valign="top"><b>备注：</b></td><td colspan="7">'.$trace['mReason'].'</td></tr>';
            $item['retain'] .='</table>';
            $item['bFinish'] = $trace['bFinish']==1 ? true : false;
            $item['content'] = '';
            $item['footer']  = [
                'left' => '修改时间:' . $trace['tLastModifyDate'] . '&nbsp;&nbsp;修改人:' . $trace['iLastModifyUserId'],
                'right' => '创建时间:' . $trace['tCreateDate'] . '&nbsp;&nbsp;创建人:' . $trace['iCreateUserId'],
                ];

            $arr[] = $item;
        }
        if($flag){
            return $arr[0];
        }
        return $arr;
    }

    public function replaceArr($str,$enums){
        $ids =explode(',',$str);
        if(count($ids) <= 0){
            return '';
        }
        $arr = [];
        foreach ($ids as $id){
            $arr[] = $enums[$id];
        }
        return implode(',',$arr);
    }

    /**
     * 反馈
     *
     *
     * create by dale 20180320
     */
    public function feedbackAction(){
        $iSBLId = $this->request->getQuery('iSBLId');
        $this->view->pick('school_book/feedback');

        Assets::importJs('js/school_book/feedback.js');
        $objs = XhsblPushLog::find([
            'conditions' => 'bDelete = 0  AND iSBLId = :iSBLId:',
            'bind'       =>  ['iSBLId' => $iSBLId],
        ])->toArray();
        $bookIds = array_column($objs,'sBookId');

        $books = $this->getBooks($bookIds);
        $newArr = [];
        foreach ($books as $book){
            $newArr = $book['book'];
        }
        $info = XhsblFeedback::find([
            'conditions' => 'bDelete = 0 AND iSBLId = :iSBLId:',
            'bind'       => ['iSBLId' => $iSBLId],
            'order'      =>  'tCreateDate desc',
        ])->toArray();
        $webArr=[
            'iSBLId' => $iSBLId,
            'books'  => $newArr,
        ];
        if(count($info) > 0){
            $webArr['info'] = $info;
        }
        $this->view->setVars($webArr);
    }


    /**
     * 获取书名接口
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180320
     */
    public function getBookAction(){
        $iSBLId = $this->request->getPost('iSBLId');
        $gradeId  = $this->request->getPost('gradeId');
        $subjectId  = $this->request->getPost('subjectId');

        $schoolId = XhsblInfo::findFirst($iSBLId)->iSchoolId;

        $url = Main::getConfigByName('resServerInterface')['questionBaseUrl'];

        $client   = new HttpClient($url);
        $response = $client->get('api/v1/books/schoolAddMyself',['schoolId'=>$schoolId]);
        if (!$response->isSuccess()){
            return $this->sendErrorResponse(500,$response->toArray()['msg'] ?:'调取学校自荐书接口失败',$response);
        }
        $books = [];
        $data = $response->toArray();
        foreach ($data as $index=>$row){  //校本库自建书
//            if($row['gradeId'] == $gradeId && $row['subjectId'] == $subjectId && $row['schoolId'] == $schoolId ){
//                $books[] = $row;
//            }
            if($row['subjectId'] == $subjectId && $row['schoolId'] == $schoolId){ //自建书没有年级
                $books[] = $row;
            }
        }
        //获取自荐书目录
        $params = [
            'gradeId' => $gradeId,
            'subjectId' => $subjectId,
        ];
        $arr = [];
        foreach ($books as $book){ //获取书目录
            $params['textBookVersion'] = $book['textBookVersion'];
            $response = $client->get('/api/v1/books/'.$book['bookId'].'/catalogs/coach',$params);
            if (!$response->isSuccess()){
                return $this->sendErrorResponse(500,$response->toArray()['msg'] ?:'调取获取书本版本接口失败',$response);
            }
            $arr[] = $response->toArray();
        }

        //------ 年级 ，学校，版本号，依次查询 其他书本

        $response = $client->get('api/v1/books/textBookVersionCompare');
        if (!$response->isSuccess()){
            return $this->sendErrorResponse(500,$response->toArray()['msg'] ?:'调取获取书本版本接口失败',$response);
        }
        $data = $response->toArray();
        $textVersions = [];
        foreach ($data as $index =>$row){
            if ($row['gradeId'] == $gradeId && $row['subjectId'] == $subjectId) {
                $textVersions[] = $row['textBookVersion'];
            }
        }
        $textVersions = array_values(array_unique($textVersions)); //版本号去重

        //循环版本号获取书目录
        $params = [
            'libraryType' => 2,
            'userId'    => Main::getLoginUserInfo('userId'),
            'gradeId'   => $gradeId,
            'subjectId' => $subjectId,
            'schoolId'  => $schoolId
        ];
        foreach ($textVersions as $index =>$textVersion){ //带有章节
            $params['textBookVersion'] = $textVersion;
            $response = $client->get('api/v1/catalogs',$params);
            if (!$response->isSuccess()){
                return $this->sendErrorResponse(500,$response->toArray()['msg'] ?:'调取获取版本书接口失败',$response);
            }
            $arr[] = $response->toArray();
        }

        foreach ($arr as $index =>$row){
            if(isset($row['catalogs']) && is_array($row['catalogs'])){
                foreach ($row['catalogs']  as $key => $val){
                    if($val['parentCatalogId'] != 0){ //去除子章节
                        unset($arr[$index]['catalogs'][$key]);
                    }
                }
                $arr[$index]['catalogs'] = array_values($arr[$index]['catalogs']);
            }
        }
        if(count($arr) <= 0){
            $books = null;
            $catalogs =null;
        }else{
            $books    = array_column($arr,'bookName','bookId');
            $catalogs = array_column($arr,'catalogs','bookId');
        }
        return $this->sendJsonResponse(['books'=>$books,'catalogs'=>$catalogs]);
    }

    /**
     *
     */
    public function saveFeedbackAction(){
        $this->view->disable();
        $startTime = $this->request->getPost('startTime');
        $endTime   = $this->request->getPost('endTime');
        $iSBLId    = $this->request->getPost('iSBLId');
        $sBookId   = $this->request->getPost('sBookId');
        if(!$startTime || !$endTime){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        try{
            $conditionArr = [
                'conditions' => 'bDelete = 0 AND tStartTime >= :tStartTime:  AND tEndTime <= :tEndTime: AND iSBLId = :iSBLId: ',
                'bind'       => ['tStartTime' => $startTime ,'tEndTime' => $endTime , 'iSBLId' => $iSBLId],
                'order'      => 'iGrade,iSubject'
            ];
            if($sBookId){
                $conditionArr['conditions'] .=' AND sBookId = :bookId:';
                $conditionArr['bind']        = array_merge($conditionArr['bind'],['bookId' =>$sBookId ]);
            };

            $logs = XhsblPushLog::find($conditionArr)->toArray();
            if(count($logs) <= 0){
                return $this->sendErrorResponse(500,'该时间段没有数据');
            }

            $arr = [];
            $bookIds = array_column($logs,'sBookId');
            $books   = $this->getBooks($bookIds);
            $gradeAndSubject = $this->getGradeSubject();
            Main::runUserNameById($logs, ['iLastModifyUserId'=>'iLastModifyUserId','iCreateUserId'=>'iCreateUserId','iChargeId'=>'iChargeId','iTchId'=>'iTchId'], true);
            foreach ($logs as $log){
                $log['iSubject'] = $gradeAndSubject['subject'][$log['iSubject']];
                $log['iGrade']   = $gradeAndSubject['grade'][$log['iGrade']];
                $log['sChapterIds'] = $this->replaceArr($log['sChapterIds'],$books[$log['sBookId']]['catalogs'] );
                $log['sBookId']  = $books[$log['sBookId']]['book'][$log['sBookId']];
                $log['bFinish']  = $log['bFinish']==1 ? '是': '否';
                $arr[] = $log;
            }
            $titleArr = [
                'iGrade'   => '年级',
                'iSubject' => '学科',
                'iTchId'   => '老师',
                'iChargeId' => '对接人',
                'sBookId'   =>'题库',
                'sChapterIds' => '章节',
                'tStartTime'  => '开始时间',
                'tEndTime'    => '结束时间',
                'iQuestionNum' => '预计题量',
                'bFinish'      => '是否完成',
            ];

            $data = [];
            foreach ($arr as $key => $row) {
                foreach ($titleArr as $filed => $name) {
                    $data[$key][$filed] = isset($row[$filed]) ? $row[$filed] : '';
                }
            }
//            Tool::exportExcelOnline()
            $url = $this->exportExcelOnline('反馈1'.$startTime.'至'.$endTime,$titleArr,$data,'xlsx',['autoWidth'=>true,'header'=>['title'=>'校本库进度（'.$startTime.'-'.$endTime.'）'],'getFile'=>true]);
            $obj =  new XhsblFeedback();
            $obj->sBookId = $sBookId ;
            $obj->iSBLId  = $iSBLId  ;
            $obj->tStartTime = $startTime;
            $obj->tEndTime   = $endTime;
            $obj->sUrl       = $url;
            if(!$obj->save()){
                return $this->sendErrorResponse(500,'保存失败');
            }
            return $this->sendSuccessResponse('成功');

        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }



    }


//    public static function exportExcelOnline($fileName, $titleArr, $data, $type = 'xlsx', $options = [])
//    {
//        $typeArr = [
//            'xlsx'  => 'Excel2007',
//            'xls'   => 'Excel5',
//            'csv'   => 'CSV',
//            'html'  => 'html'
//        ];
//        array_key_exists($type, $typeArr) or $type = 'xlsx';
//        require_once APP_PATH . '/common/library/PHPExcel/PHPExcel.php';
//        require_once APP_PATH . '/common/library/PHPExcel/PHPExcel/IOFactory.php';
//        $objPHPExcel = new \PHPExcel();
//        $objPHPExcel->setActiveSheetIndex(0);
//
//        $startRow = 1;
//        if(isset($options['header'])){
//            $startRow = 2;
//            $sheet = $objPHPExcel->getActiveSheet();
//            $sheet->getRowDimension(1)->setRowHeight(isset($options['header']['height']) ? $options['header']['height'] : 40);
//            $endChar = chr(ord('A')+count($titleArr)-1);
//            $sheet->mergeCells('A1:'.$endChar.'1');
//            $sheet->setCellValue('A1',  $options['header']['title']);
//            $sheet->getStyleByColumnAndRow('A', 1)->getFont()->setSize(isset($options['header']['fontSize']) ? $options['header']['fontSize'] : 18);
//            $sheet->getStyleByColumnAndRow('A', 1)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//            $sheet->getStyleByColumnAndRow('A', 1)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
//        }
//        //设置excel列名
//        $cell = 'A';
//        $bCell = '';
//
//        $maxLenArr = [];
//        foreach ($titleArr as $key => $title) {
//            if ($cell > 'Z') {
//                if ($bCell == '') {
//                    $bCell = 'A';
//                } else {
//                    $bCell++;
//                }
//                $cell = 'A';
//            }
//            $objPHPExcel->getActiveSheet()->setCellValue($bCell . $cell . $startRow, is_array($title) ? $title['name'] : $title);
//
//            if (isset($options['autoWidth']) && $options['autoWidth']) {
//                $maxLenArr[$cell] = strlen(is_array($title) ? $title['name'] : $title);
//            }
//            $cell++;
//        }
//
//        //把数据循环写入excel中
//        foreach($data as $key => $value){
//            $cell   = 'A';
//            $bCell  = '';
//            $key += $startRow+1;
//            foreach($value as $field => $val){
//                if($cell > 'Z'){
//                    if($bCell == '') {
//                        $bCell = 'A';
//                    }
//                    else{
//                        $bCell++ ;
//                    }
//                    $cell = 'A';
//                }
//                $objPHPExcel->getActiveSheet()->setCellValueExplicit($bCell . $cell . $key, $val);
//                if (isset($options['autoWidth']) && $options['autoWidth']) {
//                    $maxLenArr[$cell] = $maxLenArr[$cell] >= strlen($val) ? $maxLenArr[$cell] : strlen($val);
//                }
//                $cell++ ;
//            }
//            if (isset($options['height']) && $options['height']) {
//                $objPHPExcel->getActiveSheet()->getRowDimension($key)->setRowHeight($options['height']);
//            }
//        }
//
//        //自动宽度或设置宽度时定义宽
//        if (isset($options['autoWidth']) || isset($options['setWidth'])) {
//            $cell = 'A';
//            $bCell = '';
//            foreach ($titleArr as $key => $title) {
//                if ($cell > 'Z') {
//                    if ($bCell == '') {
//                        $bCell = 'A';
//                    } else {
//                        $bCell++;
//                    }
//                    $cell = 'A';
//                }
//                $width = is_array($title) && isset($title['width']) ? $title['width']
//                    : (isset($options['width']) ? $options['width'] : $maxLenArr[$cell]);
//                $objPHPExcel->getActiveSheet()->getColumnDimension($cell)->setWidth($width);
//                $cell++;
//            }
//        }
//
//        //导出代码
//        $objPHPExcel->getActiveSheet()->setTitle($fileName);
//        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, $typeArr[$type]);
//        ob_clean();
//        $fileName = md5($fileName.time()) . '.' . $type;
//        $objWriter->save(TEMP_PATH.$fileName);
//
//        $url = Main::uploadFileToOSS(TEMP_PATH.$fileName,'xlsx');
//        unlink(TEMP_PATH.$fileName);
//        return $url;
//    }

    /**
     * 返回excel 文件地址
     *
     * @param $fileName
     * @param $titleArr
     * @param $data
     * @param string $type
     * @param array $options
     *
     * @return bool|mixed
     * @throws XhException
     *
     * create by dale  20181026
     */
    public static function exportExcelOnline($fileName, $titleArr, $data, $type = 'xlsx', $options = [])
    {
        try {
            $checkType = ['xls', 'xlsx'];
            in_array($type, $checkType) or $type = 'xlsx';
            $spreadsheet = new Spreadsheet();
            $worksheet = $spreadsheet->getActiveSheet();
            $startRow = 1;
            $endChar = chr(ord('A') + count($titleArr) - 1);
            if (isset($options['header'])) { //设置头部
                $startRow = 2;
                $worksheet->mergeCells('A1:' . $endChar . '1'); //合并
                $worksheet->getStyle('A1')->applyFromArray([
                    'font' => [
                        'bold' => true
                    ],
                    'alignment' => [
                        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                        'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER
                    ],
                ])->getFont()->setSize(isset($options['header']['fontSize']) ? $options['header']['fontSize'] : 18);
                $worksheet->getRowDimension('1')->setRowHeight(isset($options['header']['height']) ? $options['header']['height'] : 40); //设置行高
                $worksheet->setCellValueByColumnAndRow(1, 1, $options['header']['title']);
            }
//            $worksheet->getDefaultColumnDimension()->setWidth(30); //默认宽度
            if (isset($options['autoWidth'])) { //自适应宽度
                for ($i = 0; $i < count($titleArr); $i++) {
                    $worksheet->getColumnDimension(chr(ord('A') + $i))->setAutoSize(true);
                }
            }
            $cell = 1;
            foreach ($titleArr as $key => $title) {
                $worksheet->setCellValueByColumnAndRow($cell, $startRow, is_array($title) ? $title['name'] : $title);
                $cell++;
            }
            foreach ($data as $key => $value) {
                $cell = 'A';
                $bCell = '';
                $key += $startRow + 1;
                foreach ($value as $field => $val) {
                    if ($cell > 'Z') {
                        if ($bCell == '') {
                            $bCell = 'A';
                        } else {
                            $bCell++;
                        }
                        $cell = 'A';
                    }
                    $worksheet->setCellValueExplicit($bCell . $cell . $key, $val, DataType::TYPE_STRING);
                    $cell++;
                }
                if (isset($options['height']) && $options['height']) {
                    $worksheet->getRowDimension($key)->setRowHeight($options['height']);
                }
            }

            //导出代码
            $worksheet->setTitle($fileName);
            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
            ob_clean();
            $fileName = md5($fileName.time()) . '.' . $type;
            $writer->save(TEMP_PATH.$fileName);
            $url = Main::uploadFileToOSS(TEMP_PATH.$fileName,'xlsx');
            unlink(TEMP_PATH.$fileName);
            return $url;
        } catch (\Exception $e) {
            throw new XhException($e->getMessage());
        }
    }

    /**
     * 删除反馈
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180324
     */
    public function delFeedbackAction(){
        try{
            $iSBFId = $this->request->getPost('nodeId');
            if(!$iSBFId){
                return $this->sendErrorResponse(400,'缺少参数');
            }
            $obj = XhsblFeedback::findFirst($iSBFId);
            if(!$obj){
                return $this->sendErrorResponse(500,'记录未找到');
            }
            $obj->bDelete = 1;
            if(!$obj->save()){
                return $this->sendErrorResponse(500,'保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }

    }

    /**
     * 校本库书本tab
     *
     * @param $sblId
     *
     * @return string
     *
     * create by dale 20180428
     */
    public function booksTabAction($sblId){
        if ( !$sblId ) {
            return $this->sendViewError('缺少参数' );
        }
        $this->view->pick('school_book/booksTab');
        $bookIds = XhsblPushLog::find([
            'columns'    => 'sBookId',
            'conditions' => 'bDelete = 0 AND iSBLId = :iSBLId: ',
            'bind'       => ['iSBLId' => $sblId],
        ])->toArray();
        $bookIds = array_values(array_filter(array_column($bookIds,'sBookId')));
        if ( count($bookIds) <= 0 ) {
            return $this->sendViewError('未获到校本库书本id');
        }
        $books = $this->getBooks($bookIds);
        $tabTitle = [];
        $tabFrame = [];
        $host = Main::getConfigByName('resServerInterface')['resManageUrl'];
        foreach ( $bookIds as $index => $bookId ){
            $bookName = $books[$bookId]['book'][$bookId];
            $bookTabName = strlen($bookName) >=  4 ? mb_substr($bookName , 0 , 4 , 'utf-8') . '...' : $bookName ; //如果字符串长度大于4，截取4
            $url = rtrim($host,'/') . '/Cloudwk/getBookCatelog?bookId=' . $bookId;
            if($index == 0){
                $tabTitle[$index] = '<li class="active"><a title="'.$bookName.'" href="#style3Tab' . intval($index+1) . '" data-toggle="tab">' . $bookTabName . '</a></li>';
                $tabFrame[$index] = '<div class="tab-pane fade in active" id="style3Tab' . intval($index+1) . '" style="height: 100%;width: 100%;">
                                        <iframe   src="' . $url . '"    style="width: 100%;height: 100%;border-style: none;padding: 0px;"  scrolling="yes"   ></iframe>
                                    </div>';
            }else{
                $tabTitle[$index] = '<li class=""><a  title="'.$bookName.'" href="#style3Tab' . intval($index+1) . '" data-toggle="tab">' . $bookTabName . '</a></li>';
                $tabFrame[$index] = '<div class="tab-pane fade " id="style3Tab' . intval($index+1) . '" style="height: 100%;width: 100%;">
                                        <iframe   src="' . $url . '"    style="width: 100%;height: 100%;border-style: none;padding: 0px;"  scrolling="yes"   ></iframe>
                                    </div>';
            }
        }
        $tab = ['tabTitle' => $tabTitle , 'tabFrame' => $tabFrame ];
        $this->view->setVars([
            'tab' => $tab,
        ]);
    }

    /**
     * 使用情况
     * create by xjq 20180514
     */
    public function useDetailAction(){
        $this->view->pick('school_book/useDetail');
        $iSBLId    = $this->request->getQuery('iSBLId' , 'string');
        $startTime = $this->request->getQuery('startTime' , 'string');
        $endTime   = $this->request->getQuery('endTime' , 'string');
        $startTime = strtotime($startTime . ' 00:00:00');
        $endTime   = strtotime($endTime . ' 23:59:59');
        if ( !$endTime || !$startTime ){
            return $this->sendViewError( '缺少参数');
        }

        $schoolId = XhsblInfo::findFirst([
            'columns'    => 'iSchoolId',
            'conditions' => 'bDelete = 0 and iSBLId = :iSBLId:',
            'bind'       => ['iSBLId' => $iSBLId]
        ])->iSchoolId;
        $objs = XhsblPushLog::find([
            'conditions' => 'bDelete = 0  AND iSBLId = :iSBLId:',
            'bind'       =>  ['iSBLId' => $iSBLId],
        ])->toArray();
        $bookIds = array_column($objs,'sBookId');

        $books = $this->getBooks($bookIds);
        $newArr = [];
        foreach ($books as $book){
            $newArr = $book['book'];
        }
        $books = $newArr;

//        $books ['59a50182e6279517d0367fbc'] = '通城学典课时作业本数七上12（RJ）';

        $arr = [];
        $baseUrl = Main::getConfigByName('resServerInterface')['cloudWorkStatUrl'];
        $client = new HttpClient($baseUrl);
        foreach ($books as $bookId =>$bookName){
            $response = $client->get("/intranet/work/statistic/schools/{$schoolId}/books/{$bookId}",[
                'startTime' => $startTime,
                'endTime'   => $endTime
            ]);
            if(!$response->isSuccess()) {
                return $this->sendErrorResponse(500 , $response->toArray()['msg'] ?: '未知错误' ,$response->toArray());
            }
            $countData = $response->toArray();
            $item = [
                'bookId'   => $bookId,
                'bookName' => $bookName,
                'data'     => $countData
            ];
            $arr[] = $item;
        }
//        var_dump($arr);die;
        $this->view->setVars([
            'arr' => $arr,
        ]);
    }

    /**
     * 教辅使用情况
     *
     * create by xjq 20180514
     */
    public function bookUseTabAction(){
        $iSBLId = $this->request->getQuery('iSBLId' , 'string');
        $this->view->pick('school_book/bookUseTab');
        Assets::importJs('js/school_book/bookUseTab.js');
        $this->view->setVars([
            'iSBLId' => $iSBLId
        ]);
    }

}